import type { FC } from 'react';
import { View } from 'react-native';
import { useSafeState, useMemoizedFn } from 'ahooks';
import Carousel from 'react-native-reanimated-carousel';
import { openZoomViewer } from '@/components';
import Resize from '@/components/Resize';
import Indicator from './indicator';
import ImageItem from './item';

type ImagesProps = {
  urls: string[];
  height?: number;
}

const Images: FC<ImagesProps> = (props) => {
  const { urls, height = 200 } = props;
  const [index, setIndex] = useSafeState(0);

  const onItemPress = useMemoizedFn((index: number) => {
    openZoomViewer({ urls, index });
  });

  const renderContent = (width: number) => {
    return (
      <View>
        <Indicator
          index={index}
          total={urls.length}
        />
        <Carousel
          data={urls}
          width={width}
          height={height}
          defaultIndex={index}
          onSnapToItem={setIndex}
          renderItem={({ item, index }) => (
            <ImageItem
              url={item}
              index={index}
              onPress={onItemPress}
            />
          )}
        />
      </View>
    );
  }

  return (
    <Resize style={{ height }}>
      {(e) => renderContent(e.width)}
    </Resize>
  );
}

export default Images;